import { login, sysProfile, sysUser } from '@/api/user'
import { getToken, setToken } from '@/utils/auth.js'
import router from '@/router'
import asyncRouter from '@/router/modules/index'
import { constantRoutes, resetRouter } from '@/router'

const state = { token: getToken() || '', userInfo: '' }
const mutations = {
  // 设置token
  SetToken(state, value) {
    state.token = value
    setToken(value)
  },
  // 设置用户信息
  setUserInfo(state, value) {
    state.userInfo = value
  },
  // 退出登录,删除token和用户信息
  logout(state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    resetRouter()
  }
}
const actions = {
  // 登录
  async toLogin(store, value) {
    const res = await login(value)
    console.log(res)
    store.commit('SetToken', res.data)
  },
  // 获取用户信息
  async getUserInfo(store) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    console.log(res)
    console.log(res2)
    // 用户信息合并
    store.commit('setUserInfo', { ...res.data, ...res2.data })
    //
    const newArr = asyncRouter.filter((item) => {
      return store.state.userInfo.roles.menus.includes(item.name)
    })
    console.log(newArr)
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    store.commit('router/setRouteList', [...constantRoutes, ...newArr], {
      root: true
    })
    router.addRoutes(newArr)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}
